//! 主题配置模块
//! 负责加载和解析Material Design 3主题配置文件
//! 创建时间：2025-10-17 作者：AI助手 目的：实现基于JSON配置文件的主题系统

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;

// 导入主题相关枚举

use crate::ThemeMode;

/// MD3标准主题配置结构
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MD3ThemeConfig {
    pub description: String,
    pub themes: HashMap<String, ThemeColors>,
}

/// 主题颜色配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemeColors {
    pub light: ColorScheme,
    pub dark: ColorScheme,
}

/// 颜色方案配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColorScheme {
    #[serde(rename = "primary")]
    pub primary: String,
    #[serde(rename = "onPrimary")]
    pub on_primary: String,
    #[serde(rename = "primaryContainer")]
    pub primary_container: String,
    #[serde(rename = "onPrimaryContainer")]
    pub on_primary_container: String,
    #[serde(rename = "secondary")]
    pub secondary: String,
    #[serde(rename = "onSecondary")]
    pub on_secondary: String,
    #[serde(rename = "secondaryContainer")]
    pub secondary_container: String,
    #[serde(rename = "onSecondaryContainer")]
    pub on_secondary_container: String,
    #[serde(rename = "tertiary")]
    pub tertiary: String,
    #[serde(rename = "onTertiary")]
    pub on_tertiary: String,
    #[serde(rename = "tertiaryContainer")]
    pub tertiary_container: String,
    #[serde(rename = "onTertiaryContainer")]
    pub on_tertiary_container: String,
    #[serde(rename = "error")]
    pub error: String,
    #[serde(rename = "onError")]
    pub on_error: String,
    #[serde(rename = "errorContainer")]
    pub error_container: String,
    #[serde(rename = "onErrorContainer")]
    pub on_error_container: String,
    #[serde(rename = "background")]
    pub background: String,
    #[serde(rename = "onBackground")]
    pub on_background: String,
    #[serde(rename = "surface")]
    pub surface: String,
    #[serde(rename = "onSurface")]
    pub on_surface: String,
    #[serde(rename = "surfaceVariant")]
    pub surface_variant: String,
    #[serde(rename = "onSurfaceVariant")]
    pub on_surface_variant: String,
    #[serde(rename = "outline")]
    pub outline: String,
    #[serde(rename = "outlineVariant")]
    pub outline_variant: String,
    #[serde(rename = "shadow")]
    pub shadow: String,
    #[serde(rename = "scrim")]
    pub scrim: String,
    #[serde(rename = "inverseSurface")]
    pub inverse_surface: String,
    #[serde(rename = "inverseOnSurface")]
    pub inverse_on_surface: String,
    #[serde(rename = "inversePrimary")]
    pub inverse_primary: String,
}

/// 主题管理器
#[derive(Debug, Clone)]
pub struct ThemeManager {
    pub config: MD3ThemeConfig,
    pub current_theme: String,
    pub current_mode: String,
}

impl ThemeManager {
    /// 从文件加载主题配置
    pub fn load_from_file(path: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let content = fs::read_to_string(path)?;
        let config: MD3ThemeConfig = serde_json::from_str(&content)?;
        
        Ok(Self {
            config,
            current_theme: "blue".to_string(),
            current_mode: "light".to_string(),
        })
    }
    
    /// 设置主题模式
    pub fn set_mode(&mut self, mode: &str) {
        self.current_mode = mode.to_string();
    }
    
    /// 设置主题颜色
    pub fn set_theme(&mut self, theme: &str) {
        self.current_theme = theme.to_string();
    }
    
    /// 获取当前颜色方案
    pub fn get_current_scheme(&self) -> &ColorScheme {
        if let Some(theme_colors) = self.config.themes.get(&self.current_theme) {
            match self.current_mode.as_str() {
                "dark" => &theme_colors.dark,
                _ => &theme_colors.light,
            }
        } else {
            // 默认返回蓝色主题的亮色方案
            &self.config.themes.get("blue").unwrap().light
        }
    }
    
    /// 根据主题和模式获取颜色方案
    pub fn get_color_scheme(&self, theme: Theme, theme_mode: ThemeMode) -> &ColorScheme {
        let theme_name = match theme {
            Theme::Red => "red",
            Theme::Blue => "blue",
            Theme::Green => "green",
            Theme::Orange => "orange",
            Theme::Purple => "purple",
        };
        
        let mode = match theme_mode {
            ThemeMode::Light => "light",
            ThemeMode::Dark => "dark",
        };
        
        if let Some(theme_colors) = self.config.themes.get(theme_name) {
            match mode {
                "dark" => &theme_colors.dark,
                _ => &theme_colors.light,
            }
        } else {
            // 默认返回红色主题的亮色方案
            &self.config.themes.get("red").unwrap().light
        }
    }
    
    /// 从十六进制颜色字符串转换为egui::Color32
    pub fn hex_to_color32(hex: &str) -> Result<egui::Color32, Box<dyn std::error::Error>> {
        let hex = hex.trim_start_matches('#');
        
        if hex.len() != 6 {
            return Err("Invalid hex color format".into());
        }
        
        let r = u8::from_str_radix(&hex[0..2], 16)?;
        let g = u8::from_str_radix(&hex[2..4], 16)?;
        let b = u8::from_str_radix(&hex[4..6], 16)?;
        
        Ok(egui::Color32::from_rgb(r, g, b))
    }
    
    /// 获取主色调
<<<<<<< HEAD
    pub fn get_primary_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = &scheme.primary;
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取主容器色
    pub fn get_primary_container_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = &scheme.primary_container;
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
=======
    pub fn get_primary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.primary).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取主容器色
    pub fn get_primary_container_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.primary_container).unwrap_or_else(|_| self.get_default_color())
>>>>>>> 35f018f0061274a994b7f9fda7e3edcf141f9215
    }
    
    /// 获取次色调
    pub fn get_secondary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.secondary).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取次容器色
    pub fn get_secondary_container_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.secondary_container).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取第三色调
<<<<<<< HEAD
    pub fn get_tertiary_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = &scheme.tertiary;
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取第三容器色
    pub fn get_tertiary_container_color(&self, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme_mode).unwrap_or_else(|_| self.get_default_scheme(theme_mode));
        let color_value = &scheme.tertiary_container;
        
        ThemeManager::hex_to_color32(color_value).unwrap_or_else(|_| self.get_default_color())
=======
    pub fn get_tertiary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.tertiary).unwrap_or_else(|_| self.get_default_color())
    }
    
    /// 获取第三容器色
    pub fn get_tertiary_container_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.tertiary_container).unwrap_or_else(|_| self.get_default_color())
>>>>>>> 35f018f0061274a994b7f9fda7e3edcf141f9215
    }
    
    /// 获取表面色
    pub fn get_surface_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.surface).unwrap_or_else(|_| self.get_default_surface_color())
    }
    
    /// 获取表面变体色
    pub fn get_surface_variant_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.surface_variant).unwrap_or_else(|_| self.get_default_surface_color())
    }
    
    /// 获取表面上的文本颜色
    pub fn get_on_surface_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_surface).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取表面变体上的文本颜色
    pub fn get_on_surface_variant_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_surface_variant).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取错误色
    pub fn get_error_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.error).unwrap_or_else(|_| self.get_default_error_color())
    }
    
    /// 获取轮廓色
    pub fn get_outline_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.outline).unwrap_or_else(|_| self.get_default_outline_color())
    }
    
    /// 获取背景色
    pub fn get_background_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.background).unwrap_or_else(|_| self.get_default_surface_color())
    }
    
    /// 获取表面上的文字颜色
    pub fn get_on_background_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_background).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取主色调上的文字颜色
    pub fn get_on_primary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_primary).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取次色调上的文字颜色
    pub fn get_on_secondary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_secondary).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取第三色调上的文字颜色
    pub fn get_on_tertiary_color(&self, theme: Theme, theme_mode: ThemeMode) -> egui::Color32 {
        let scheme = self.get_color_scheme(theme, theme_mode);
        ThemeManager::hex_to_color32(&scheme.on_tertiary).unwrap_or_else(|_| self.get_default_text_color())
    }
    
    /// 获取默认颜色（用于错误处理）
    fn get_default_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(59, 130, 246) // 默认蓝色作为主题色
    }
    
    /// 获取默认表面颜色（用于错误处理）
    fn get_default_surface_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(253, 251, 255) // 默认白色背景
    }
    
    /// 获取默认文本颜色（用于错误处理）
    fn get_default_text_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(27, 27, 31) // 默认深色文本
    }
    
    /// 获取默认错误颜色（用于错误处理）
    fn get_default_error_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(186, 26, 26) // 默认红色错误色
    }
    
    /// 获取默认轮廓颜色（用于错误处理）
    fn get_default_outline_color(&self) -> egui::Color32 {
        egui::Color32::from_rgb(116, 119, 127) // 默认灰色轮廓
    }
    
    /// 获取所有可用的主题名称
    pub fn get_available_themes(&self) -> Vec<(String, String)> {
        let mut themes: Vec<(String, String)> = self.config.themes
            .keys()
            .map(|name| (name.clone(), self.get_theme_display_name(name)))
            .collect();
        
        // 按照特定顺序排序：红、蓝、绿、橙、紫
        themes.sort_by(|a, b| {
            let order = |name: &str| -> usize {
                match name {
                    "red" => 0,
                    "blue" => 1,
                    "green" => 2,
                    "orange" => 3,
                    "purple" => 4,
                    _ => 5,
                }
            };
            order(&a.0).cmp(&order(&b.0))
        });
        
        themes
    }
    
    /// 获取主题显示名称
    fn get_theme_display_name(&self, theme_name: &str) -> String {
        match theme_name {
            "red" => "红色".to_string(),
            "blue" => "蓝色".to_string(),
            "green" => "绿色".to_string(),
            "orange" => "橙色".to_string(),
            "purple" => "紫色".to_string(),
            _ => theme_name.to_string(),
        }
    }
}

/// 默认主题管理器实例
pub fn create_default_theme_manager() -> Result<ThemeManager, Box<dyn std::error::Error>> {
<<<<<<< HEAD
    ThemeManager::load_from_file("d:\\work\\mtimer\\mido-timer\\timer_themes.json")
=======
    ThemeManager::load_from_file("docs/md3-standard-theme.json")
>>>>>>> 35f018f0061274a994b7f9fda7e3edcf141f9215
}